package com.baizhi.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//注解用于标识或者描述AOP中的切面类型，基于切面类型构建的对象用于为目标对象进行功能扩展或控制目标对象的执行。
@Aspect
//将对象交给spring容器管理
@Component
@Slf4j
public class CacheAopUpdate {


    @Autowired
    private JedisCluster jedisCluster;

    @Around("@annotation(cacheFindUpdate)")
    public void around(ProceedingJoinPoint jp, CacheFindUpdate cacheFindUpdate) throws Throwable{
        MethodSignature methodSignature = (MethodSignature)jp.getSignature();
        Method method = methodSignature.getMethod();
        log.info(method.getName()+"方法被AOP成功拦截,继续执行AOP中的程序");
        Object result=null;
        //1.获取key
        String key = cacheFindUpdate.key();
        log.info("通过注解获取的键:"+key);
        List<String> ListKey = new ArrayList<>();
        //获取所有Redis连接池
        Map<String, JedisPool> node = jedisCluster.getClusterNodes();
        //遍历所有连接池，逐个进行模糊查询
        for(String k : node.keySet()){
            //从连接池中获取连接
            JedisPool pool = node.get(k);
            //通过连接获取Redis节点
            Jedis connection = pool.getResource();
            try {
                //从Redis节点中获取key
                ListKey.addAll(connection.keys(key+"*"));
            } catch(Exception e){
                log.error("获取key异常", e);
            } finally{
                log.info("关闭连接");
                connection.close();   //一定要关闭连接！
            }
        }
        for (String k:ListKey){
            log.info("集群中的key----"+k);
            jedisCluster.del(k);
        }
        //执行目标方法
        jp.proceed();


    }


}
